import { markRaw } from "vue";
import type { Component } from "vue";

import StarrocksCpsForm from "./starrocks/StarrocksCpsForm.vue";
import StarrocksGenericDataQualityForm from "./starrocks/StarrocksGenericDataQualityForm.vue";
import StarrocksCpsBaseStatisticsForm from "./starrocks/StarrocksCpsBaseStatisticsForm.vue";
import StarrocksClusterComparisonForm from "./starrocks/StarrocksClusterComparisonForm.vue";
import KafkaTopicNoUpdateForm from "./kafka/KafkaTopicNoUpdateForm.vue";
import StarrocksTableGrowthForm from "./starrocks/StarrocksTableGrowthForm.vue";

export type TemplateGroup =
  | "starrocks"
  | "kafka"
  | "flink"
  | "alerts"
  | "mixed";

export interface TemplateMeta {
  templateCode: string;
  templateName: string;
  group: TemplateGroup;
  description?: string;
  formComponent: Component;
  defaultParams: Record<string, any>;
  displayFields?: string[];
}

const cpsDefaultParams = {
  data_source_config: {
    data_source_id: null,
  },
  platform_selection: {
    selected_platforms: ["dy"],
    include_summary: true,
  },
  time_filter: {
    time_range_type: "all",
    time_start: null,
    time_end: null,
  },
  threshold_config: {
    sync_rate_threshold: 80,
  },
  display_fields: [
    "platform_summary",
    "platform",
    "source_total_count",
    "dws_total_count",
    "dws_on_sale_count",
    "dws_off_sale_count",
    "sync_rate",
    "data_status",
  ],
  field_labels: {},
  use_chinese_platform_name: true,
};

const genericDataQualityDefaultParams = {
  source_tables: {
    data_source_id: null,
    databases: [
      {
        database_name: "",
        table_names: [],
        tables: [
          {
            table_name: "",
            distinct_field: "id",
            time_field: "etl_date",
            use_distinct: true,
          },
        ],
      },
    ],
    time_range_type: "all",
    time_start: null,
    time_end: null,
  },
  target_table_config: {
    data_source_id: null,
    database_name: "",
    table_name: "",
    join_field: "id",
    time_field: "etl_date",
    filter_conditions: [],
    stat_fields: {},
  },
  filter_rules: {
    sync_rate_threshold: 80,
  },
  display_fields: [
    "source_total_count",
    "target_total_count",
    "sync_rate",
    "data_status",
  ],
  field_labels: {
    source_total_count: "源表总数",
    target_total_count: "目标表总数",
    sync_rate: "同步率",
    data_status: "数据状态",
  },
  stat_field_mappings: {},
};

const cpsBaseStatisticsDefaultParams = {
  data_source_config: {
    data_source_id: null,
  },
  platform_filter: {
    selected_platforms: ["dy", "tb", "jd", "pdd"],
  },
  time_comparison: {
    comparison_type: "day",
    base_date: null,
    compare_date: null,
  },
  display_fields: [
    "data_comment",
    "platform",
    "base_date_count",
    "compare_date_count",
    "increment",
    "growth_rate",
    "trend",
  ],
};

// 新增报表默认参数
const clusterComparisonDefaultParams = {
  source_cluster_config: { data_source_id: null },
  target_cluster_config: { data_source_id: null },
  table_selection: {
    selection_type: "specific_tables",
    database_name: "",
    table_names: [],
  },
  display_fields: [
    "table_name",
    "source_rows",
    "source_size",
    "target_rows",
    "target_size",
    "row_diff",
    "size_diff",
    "diff_rate",
  ],
};

const topicNoUpdateDefaultParams = {
  kafka_cluster_config: { cluster_id: null },
  topic_selection: { topic_names: [] },
  time_thresholds: {
    thresholds: ["1_day"],
    sort_by_staleness: true,
  },
  display_fields: [
    "topic_name",
    "partition_id",
    "last_message_time",
    "hours_no_update",
    "status",
  ],
};

const tableGrowthDefaultParams = {
  starrocks_cluster_config: { cluster_id: null },
  table_selection: {
    selection_type: "specific_tables",
    database_names: [],
    table_names: [],
  },
  statistics_config: {
    stat_type: "full_report",
    top_n: 10,
    sort_by: "row_increment",
  },
  time_dimension: {
    dimension_type: "last_day",
  },
  display_fields: [
    "database",
    "table",
    "current_rows",
    "current_size",
    "row_increment",
    "size_increment",
    "growth_status",
  ],
};

export const templateRegistry: Record<string, TemplateMeta> = {
  cps_data_quality_monitor: {
    templateCode: "cps_data_quality_monitor",
    templateName: "CPS 数据质量监控报表",
    group: "starrocks",
    description: "支持多平台选择与时间筛选的 CPS 监控报表",
    formComponent: markRaw(StarrocksCpsForm),
    defaultParams: cpsDefaultParams,
    displayFields: cpsDefaultParams.display_fields,
  },
  generic_data_quality_monitor: {
    templateCode: "generic_data_quality_monitor",
    templateName: "通用数据质量监控报表",
    group: "starrocks",
    description:
      "通用数据质量监控报表，支持多源表、单目标表、可选筛选条件、可选统计字段，适用于各种业务场景",
    formComponent: markRaw(StarrocksGenericDataQualityForm),
    defaultParams: genericDataQualityDefaultParams,
    displayFields: genericDataQualityDefaultParams.display_fields,
  },
  cps_base_statistics_report: {
    templateCode: "cps_base_statistics_report",
    templateName: "CPS基础表统计报表",
    group: "starrocks",
    description:
      "统计各平台在两个时间点的商品增量情况，支持天/月/年对比。通过对比基准日期和对比日期的商品总数，计算增量、环比增长率等关键指标",
    formComponent: markRaw(StarrocksCpsBaseStatisticsForm),
    defaultParams: cpsBaseStatisticsDefaultParams,
    displayFields: cpsBaseStatisticsDefaultParams.display_fields,
  },
  // 新增报表
  starrocks_cluster_comparison_report: {
    templateCode: "starrocks_cluster_comparison_report",
    templateName: "StarRocks集群对比报表",
    group: "starrocks",
    description: "对比两个StarRocks集群相同表的数据量，支持行数、数据大小对比",
    formComponent: markRaw(StarrocksClusterComparisonForm),
    defaultParams: clusterComparisonDefaultParams,
    displayFields: clusterComparisonDefaultParams.display_fields,
  },
  kafka_topic_no_update_report: {
    templateCode: "kafka_topic_no_update_report",
    templateName: "Kafka Topic无新增监控报表",
    group: "kafka",
    description:
      "监控Kafka Topic的新增情况，检测哪些Topic在指定时间内没有新的消息",
    formComponent: markRaw(KafkaTopicNoUpdateForm),
    defaultParams: topicNoUpdateDefaultParams,
    displayFields: topicNoUpdateDefaultParams.display_fields,
  },
  starrocks_table_growth_report: {
    templateCode: "starrocks_table_growth_report",
    templateName: "StarRocks表数据增长统计报表",
    group: "starrocks",
    description:
      "统计StarRocks表的数据增长情况，支持无新增表筛选、增量TOP排序、全量报表",
    formComponent: markRaw(StarrocksTableGrowthForm),
    defaultParams: tableGrowthDefaultParams,
    displayFields: tableGrowthDefaultParams.display_fields,
  },
};

export const templateGroups: Record<TemplateGroup, string> = {
  starrocks: "StarRocks",
  kafka: "Kafka",
  flink: "Flink",
  alerts: "通知/告警",
  mixed: "综合",
};

export const listTemplatesByGroup = () => {
  const grouped: Record<TemplateGroup, TemplateMeta[]> = {
    starrocks: [],
    kafka: [],
    flink: [],
    alerts: [],
    mixed: [],
  };

  Object.values(templateRegistry).forEach((meta) => {
    grouped[meta.group] = grouped[meta.group] || [];
    grouped[meta.group].push(meta);
  });

  return Object.entries(grouped)
    .filter(([, items]) => items.length)
    .map(([group, items]) => ({
      group,
      label: templateGroups[group as TemplateGroup] || group,
      templates: items,
    }));
};

export const getTemplateMeta = (templateCode?: string) => {
  if (!templateCode) return null;
  return templateRegistry[templateCode] || null;
};
